# 作者：宋安康
# 开发时间：2023/6/8 15:58
from os.path import commonprefix
from posixpath import split
import socket
#建立聊天回复字典
words={'how are you?':'Fine,thank you.',
        'how old are you?':'18',
        'what is your name?':'xiaoming',
        'which subject do you like?':'computer science',
        'bye':'Bye'}
s =socket.socket()
s.bind(('127.0.0.1',8000))
s.listen(1)
clientsocket,clientaddress= s.accept()
print('Connection from',clientaddress)
#开始聊天
while True:
    data=clientsocket.recv(1024).decode()
    if not data:
        break
    print('Received:',data)
    i=0
    key=''
    for k in words.keys():
        data=' '.join(data.split())
        if len(commonprefix([k,data]))>len(k)*0.75:
            key=k
            break
        length=len(set(data.split())&set(k.split()))
        if length>i:
            i=length
            key=k
    clientsocket.sendall(words.get(key, 'Sorry,can\'t find the question').encode())
clientsocket.close()

